package org.ngmj.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;
import org.ngmj.config.Config;
import org.ngmj.message.Message;

import java.util.List;

@Slf4j
@ChannelHandler.Sharable
public class MessageCodecSharable extends MessageToMessageCodec<ByteBuf, Message> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, List<Object> list) throws Exception {
        ByteBuf byteBuf = channelHandlerContext.alloc().buffer();
        byteBuf.writeBytes(new byte[]{1, 2, 3, 4});
        byteBuf.writeByte(1);
        // 序列化方式 0JDK 1JSON
        byteBuf.writeByte(Config.getSerializerAlgorithm().ordinal());
        //  指令类型
        byteBuf.writeByte(message.getMessageType());
        // 序列号
        byteBuf.writeInt(message.getSequenceId());

        // 无意义字符
        byteBuf.writeByte(0xff);
        byte[] bytes = Config.getSerializerAlgorithm().serialize(message);
        // 消息长度
        byteBuf.writeInt(bytes.length);
        //  消息
        byteBuf.writeBytes(bytes);
        list.add(byteBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int magicNum = byteBuf.readInt();
        byte version = byteBuf.readByte();
        byte serializerType = byteBuf.readByte();
        byte messageType = byteBuf.readByte();
        int sequenceId = byteBuf.readInt();
        byteBuf.readByte();
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes, 0, length);
        Serialize.SerializerAlgorithm algorithm = Serialize.getByInt(serializerType);
        // 确定具体消息类型
        Class<? extends Message> messageClass = Message.getMessageClass(messageType);
        Message message = algorithm.deserialize(bytes, messageClass);
//        log.info("{}, {}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, sequenceId, length);
//
//        log.info("{}", message);
        list.add(message);
    }
}
